package es.onlysolutions.gs.web.controller;

import es.onlysolutions.arq.core.mvc.command.AbstractCommandBean;
import es.onlysolutions.arq.core.accesobd.IEntityId;
import es.onlysolutions.gs.web.commandBean.RegisterBean;
import es.onlysolutions.gs.comm.facade.UserFacade;
import es.onlysolutions.gs.comm.entity.User;
import es.onlysolutions.gs.comm.utils.PasswordUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.validation.BindException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

/**
 * Controller to create new accounts.
 */
public class RegisterController extends GSController
{

    /**
     * The logger of this class.
     */
    private static final Log logger = LogFactory.getLog(RegisterController.class);

    private UserFacade userFacade;

    public void setUserFacade(UserFacade userFacade)
    {
        this.userFacade = userFacade;
    }

    protected AbstractCommandBean loadPage(HttpServletRequest httpServletRequest) throws Exception
    {
        return new RegisterBean();
    }

    protected ModelAndView onSubmit(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object command, BindException e) throws Exception
    {
        RegisterBean bean = (RegisterBean) command;

        User userToSave = (User) bean.getEntidad(); 
        userToSave.setPassword( PasswordUtils.encryptPassword(userToSave.getPassword()) );

        IEntityId entity = userFacade.guardar( userToSave );

        if( logger.isInfoEnabled() )
        {
            logger.info("User saved/updated. " + entity);
        }

        return new ModelAndView( getSuccessView(), getCommandName(), bean );
    }
}
